from rest_framework import serializers
from .models import WeeklyTodo


class WeeklyTodoSerializer(serializers.ModelSerializer):
    """周会待办事项序列化器"""
    
    class Meta:
        model = WeeklyTodo
        fields = [
            'id',
            'responsible_person',
            'task',
            'planned_completion_time',
            'delayed_completion_time',
            'closure',
            'remarks',
            'created_at',
            'updated_at'
        ]
        read_only_fields = ['id', 'created_at', 'updated_at']
    
    def validate_responsible_person(self, value):
        """验证责任人字段"""
        if not value or not value.strip():
            raise serializers.ValidationError("责任人不能为空")
        return value.strip()
    
    def validate_task(self, value):
        """验证事项内容字段"""
        if not value or not value.strip():
            raise serializers.ValidationError("事项内容不能为空")
        return value.strip()
    
    def validate_planned_completion_time(self, value):
        """验证计划完成时间字段"""
        # 允许空值
        if not value or not value.strip():
            return None
        return value.strip()
    
    def validate_delayed_completion_time(self, value):
        """验证推迟完成时间字段"""
        # 允许空值
        if not value or not value.strip():
            return None
        return value.strip()
    
    def validate_closure(self, value):
        """验证闭环状态字段"""
        # 允许空值，如果为空则使用默认值
        if not value or not value.strip():
            return '非闭环'
        
        valid_choices = ['非闭环', '已闭环']
        if value not in valid_choices:
            raise serializers.ValidationError(f"闭环状态必须是以下选项之一：{', '.join(valid_choices)}")
        return value